﻿using Microsoft.AspNetCore.HttpLogging;

namespace Cngot.Extensions.Logger
{
    internal class HttpLoggingInterceptor : IHttpLoggingInterceptor
    {
        public ValueTask OnRequestAsync(HttpLoggingInterceptorContext logContext)
        {
            {
                logContext.AddParameter("RequestTime", DateTimeOffset.Now.ToLocalTime());
                logContext.AddParameter("RequestMethod", logContext.HttpContext.Request.Method);
            }
            //  if (logContext.HttpContext.Request.Path.Value?.StartsWith("/req-") == true)
            {
                logContext.AddParameter("RequestPath", logContext.HttpContext.Request.Path.Value + logContext.HttpContext.Request.QueryString);
            }

            return ValueTask.CompletedTask;
        }

        public ValueTask OnResponseAsync(HttpLoggingInterceptorContext logContext)
        {
            //if (logContext.HttpContext is { Response.StatusCode: >= 200 and < 300, Request.Path.Value: "/hello" })
            //{
            //  logContext.TryDisable(HttpLoggingFields.All);
            //}
            logContext.AddParameter("StatusCode", logContext.HttpContext.Response.StatusCode);
            return ValueTask.CompletedTask;
        }
    }

    internal class HttpRemoveLogEventFilter : ILogEventFilter
    {
        private readonly string[] propertiesToRemove = new[] { "RequestId", "ConnectionId" };

        public bool IsEnabled(LogEvent logEvent)
        {
            foreach (var prop in propertiesToRemove)
            {
                if (logEvent.Properties.ContainsKey(prop))
                {
                    logEvent.RemovePropertyIfPresent(prop);
                }
            }
            return true; // 返回 true 表示保留日志事件
        }
    }
}
